package com.jinmdz.fmis.core.util;

import java.io.*;

/**
 * 本机运行环境配置工具类
 *
 * @author LiCongLu
 * @date 2021-08-07 14:30
 */
public final class ProcessUtil {

    /**
     * 获取操作系统名称，小写状态
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-04-14 14:44
     */
    public static String getOSName() {
        String osName = System.getProperty("os.name");
        if (osName != null) {
            osName = osName.toLowerCase();
        }
        return osName;
    }

    /**
     * 执行Linux环境命令
     * 默认，返回null
     *
     * @param cmd 命令字符串
     * @return
     * @author LiCongLu
     * @date 2021-08-07 14:34
     */
    public static String executeCmdForLinux(String cmd) {
        try {
            System.out.println("got cmd job : " + cmd);
            Runtime run = Runtime.getRuntime();
            Process process = run.exec(cmd);
            InputStream inputStream = process.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            byte[] b = new byte[8192];
            for (int n; (n = inputStream.read(b)) != -1; ) {
                stringBuffer.append(new String(b, 0, n));
            }
            inputStream.close();
            process.destroy();
            return stringBuffer.toString();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    /**
     * 获取序列号
     * 默认，返回null
     *
     * @param cmd    命令语句
     * @param record 要查看的字段
     * @param symbol 分隔符
     * @return
     * @author LiCongLu
     * @date 2020-04-14 14:41
     */
    public static String getSerialNumberForLinux(String cmd, String record, String symbol) {
        String execResult = executeCmdForLinux(cmd);
        if (execResult == null) {
            return null;
        }
        try {
            String[] infoArray = execResult.split("\n");
            for (String info : infoArray) {
                info = info.trim();
                if (info.indexOf(record) != -1) {
                    info.replace(" ", "");
                    String[] numbers = info.split(symbol);
                    return numbers[1];
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    /**
     * 获取处理器ID，即CPU序列号
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-04-14 14:46
     */
    public static String getProcessorId() {
        String processorId = "";
        if ("linux".equals(getOSName())) {
            processorId = getSerialNumberForLinux("dmidecode -t processor | grep 'ID'", "ID", ":");
        } else {
            processorId = getProcessorIdForWindows();
        }
        // 去除空格
        if (processorId != null) {
            processorId = processorId.replace(" ", "");
        }
        return processorId;
    }

    /**
     * 获取微软windows系列的处理器ID，即CPU序列号
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-04-14 14:48
     */
    private static String getProcessorIdForWindows() {
        String result = "";
        try {
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter writer = new java.io.FileWriter(file);
            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n"
                    + "   (\"Select * from Win32_Processor\") \n"
                    + "For Each objItem in colItems \n"
                    + "    Wscript.Echo objItem.ProcessorId \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            // + "    exit for  \r\n" + "Next";
            writer.write(vbs);
            writer.close();
            String path = file.getPath().replace("%20", " ");
            Process process = Runtime.getRuntime().exec(
                    "cscript //NoLogo " + path);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            reader.close();
            file.delete();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        if (result.trim().length() < 1 || result == null) {
            result = "";
        }
        return result.trim();
    }
}
